package com.example.cardgame

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import com.example.cardgame.model.CardMatchingGame

class Cardactivity : AppCompatActivity(), View.OnClickListener {
    private var highScore=0
    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<View>()
    // 重写 onCreate 方法
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cardgame)
        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
    // 初始化卡片按钮
        for (v in gridLayout.children) {
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        // 初始化游戏
        game = CardMatchingGame(cardButtons.count())
        updateUI()
        val reset = findViewById<Button>(R.id.reset)
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }
        // 返回主界面按钮点击事件
        val btnReturn: Button = findViewById(R.id.back)
        btnReturn.setOnClickListener {
            highScore = calculateHighScore()
            val intent = Intent()
            intent.putExtra("highScore", highScore)
            setResult(RESULT_OK, intent)
            finish()
        }
    }
// 重写 updateUI 方法
    fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
            val button = gridLayout.getChildAt(index) as Button
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundResource(R.color.purple_200)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.first)
            }
        }
    // 更新分数
        val score = findViewById<TextView>(R.id.Score)
        score.text = String.format("Score: %d", game.score)
    }
// 重写 onClick 方法
    override fun onClick(v: View?) {
        if (v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
// 重写 calculateHighScore 方法
    private fun calculateHighScore(): Int {
        // 计算最高分的逻辑
        return game.score// 示例分数
    }
}